package com.superzlc.miniweb.comn;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

public class Util {

	public static void _download(HttpServletResponse response, File file) throws IOException {
		long fileLength = file.length();

		response.setContentType("application/octet-stream");
		response.setHeader("Content-disposition", "attachment; filename="
				+ new String(file.getName().getBytes("utf-8"), "ISO8859-1"));
		response.setHeader("Content-Length", String.valueOf(fileLength));

		BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
				file));
		BufferedOutputStream bos = new BufferedOutputStream(
				response.getOutputStream());
		int bytesRead;
		byte[] buff = new byte[1024 * 4];
		while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
			bos.write(buff, 0, bytesRead);
		}
		bis.close();
		bos.flush();
		bos.close();
	}

	public static String[] readAsStrings(InputStream is, String encode) throws IOException {
		List<String> list = new ArrayList<String>();
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				is, encode));
		String tempString = null;
		while ((tempString = reader.readLine()) != null) {
			list.add(tempString);
		}
		reader.close();
		return list.toArray(new String[0]);
	}

	public static String[] readAsStrings(File file) throws IOException {
		List<String> list = new ArrayList<String>();
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				new FileInputStream(file), "UTF-8"));
		String tempString = null;
		while ((tempString = reader.readLine()) != null) {
			list.add(tempString);
		}
		reader.close();
		return list.toArray(new String[0]);
	}

	public static String readString(File file) throws IOException {
		StringBuffer sb = new StringBuffer();
		InputStreamReader in = new InputStreamReader(new FileInputStream(file),"UTF-8");
		char[] chars = new char[1024];
		int len = 0;
		while ((len = in.read(chars)) != -1) {
			sb.append(chars, 0, len);
		}
		in.close();
		return sb.toString();
	}

	public static void wirteString(File file, String content) throws IOException {
		OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(file),"UTF-8");
		out.write(content);
        out.flush();
        out.close();
	}

}
